/*
 * 官网地站:http://www.mob.com
 * 技术支持QQ: 4006852216
 * 官方微信:ShareSDK   （如果发布新版本的话，我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题，也可以通过微信与我们取得联系，我们将会在24小时内给予回复）
 *
 * Copyright (c) 2013年 mob.com. All rights reserved.
 */

package com.longrise.android.byjk.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.MessageConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.request.WXUserRequest;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.PrintLog;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import org.json.JSONObject;


/**
 * 微信客户端回调activity示例
 */
public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";

    private IWXAPI mIwxapi;

    private Handler mHandler = new Handler();

    /**
     * 处理微信发出的向第三方应用请求app message
     * <p>
     * 在微信客户端中的聊天页面有“添加工具”，可以将本应用的图标添加到其中 此后点击图标，下面的代码会被执行。Demo仅仅只是打开自己而已，但你可
     * 做点其他的事情，包括根本不打开任何页面
     */
    public void onGetMessageFromWXReq(WXMediaMessage msg) {
        Intent iLaunchMyself = getPackageManager().getLaunchIntentForPackage(getPackageName());
        startActivity(iLaunchMyself);
    }

    /**
     * 处理微信向第三方应用发起的消息
     * <p>
     * 此处用来接收从微信发送过来的消息，比方说本demo在wechatpage里面分享
     * 应用时可以不分享应用文件，而分享一段应用的自定义信息。接受方的微信 客户端会通过这个方法，将这个信息发送回接收方手机上的本demo中，当作 回调。
     * <p>
     * 本Demo只是将信息展示出来，但你可做点其他的事情，而不仅仅只是Toast
     */
    public void onShowMessageFromWXReq(WXMediaMessage msg) {
        if (msg != null && msg.mediaObject != null && (msg.mediaObject instanceof WXAppExtendObject)) {
            WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject;
            Toast.makeText(this, obj.extInfo, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIwxapi = WXAPIFactory.createWXAPI(this, UserInfor.getInstance().APP_ID, false);
        mIwxapi.handleIntent(getIntent(), this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        PrintLog.d(TAG, "resp.errCode:" + req.toString());

    }




    @Override
    public void onResp(BaseResp resp) {

        PrintLog.d(TAG, "resp.errCode:" + resp.errCode);
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    String code = "";
                    try {
                        // 获取到 code
                        code = ((SendAuth.Resp) resp).code;
                    } catch (Exception e) {
                    }
                    // 通过code获取到access_token
                    String appId = UserInfor.getInstance().APP_ID;
                    String secret = UserInfor.getInstance().secret;
                    final String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
                    new Thread() {
                        public void run() {
                            getWXAccess_Token(url);
                        }

                        ;
                    }.start();
                    break;

                default:
                    break;

            }
            if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
                PrintLog.d(TAG, "resp.errCode:" + resp.errCode);
            }else {
                super.onResp(resp);//一定要加super，实现我们的方法，否则不能回调
            }

    }

    /**
     * 通知server
     */
    private void weChardBundle(String openid, final String name) {
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("openid ", openid);
        bean.set("weixinnickname", name);
        EntityBean bean2 = new EntityBean();
        bean2.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_user_uWxBind", bean2, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                EntityBean bean = (EntityBean) result;
                UserInfor.getInstance().setWenxinstatus(bean.getString("resultstate"));
                UserInfor.getInstance().setmWXName(name);
                UserInfor.getInstance().setWeixinnickname(name);
                WXEntryActivity.this.sendBroadcast(new Intent(MessageConstants.WX_BUNDLE_));
            }

            @Override
            public void onFinished(String key, String service) {
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(WXEntryActivity.this, getString(R.string.networkerror), Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        mIwxapi.handleIntent(intent, this);
        finish();
    }

    /**
     * 刷新token
     */
    private void refresh_Token(String refresh_token) {
        String appidString = UserInfor.getInstance().APP_ID;
        final String urlString = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appidString + "&grant_type=refresh_token&refresh_token=" + refresh_token;
        new Thread() {
            public void run() {
                try {
                    final JSONObject refrestJsonObject = WXUserRequest.getInstance().getWX(urlString);
                    if (refrestJsonObject != null) {
                        String access_token = refrestJsonObject.getString("access_token");
                        String openidString = refrestJsonObject.getString("openid");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();

    }

    /**
     * 通过code获取access_token openid 然后拿去userInfor
     */
    private void getWXAccess_Token(String url) {
        try {
            final JSONObject access_token = WXUserRequest.getInstance().getWX(url);
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (access_token != null) {
                            String token = access_token.getString("access_token");
                            String openid = access_token.getString("openid");

                            // 刷新使用
                            // String refreshtoken =
                            // access_token.getString("refresh_token");
                            // refresh_Token(refreshtoken);
                            final String userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid;
                            // 获取userInfor
                            new Thread() {
                                public void run() {
                                    getWXUserInfor(userurl);
                                }

                            }.start();
                        } else {
                            //请求超时
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getWXUserInfor(String url) {
        try {
            // 根据access_token获取 userInfor
            final JSONObject userInfor = WXUserRequest.getInstance().getWX(url);
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (userInfor != null) {
                            String openid = userInfor.getString("openid");
                            String name = userInfor.getString("nickname"); // 昵称
                            // 微信
                            weChardBundle(openid, name);
                        } else {
                            //请求超时
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
